package content

import (
	"context"
	"gf_blog_admin/internal/dao"
	"gf_blog_admin/internal/model"
	"gf_blog_admin/internal/service"
	"gf_blog_admin/utility/utils"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
)

type sSlideshow struct{}

func init() {
	service.RegisterSlideshow(NewSlideshow())
}

func NewSlideshow() *sSlideshow {
	return &sSlideshow{}
}

func (s *sSlideshow) List(ctx context.Context, in *model.SlideshowListInput) (out []*model.SlideshowItem, total int, err error) {
	var (
		cls = dao.BlSlideshow.Columns()
		m   = dao.BlSlideshow.Ctx(ctx)
	)

	if in.Keywords != "" {
		m = m.WhereLike(cls.SlideTitle, in.Keywords+"%")
	}

	out = make([]*model.SlideshowItem, 0)
	err = m.OrderDesc(cls.SlideSort).OrderDesc(cls.Id).
		Page(in.Page, in.PageSize).
		Fields(cls.Id, cls.SlideTitle, cls.SlideImage, cls.SlideDesc, cls.SlideLink, cls.SlideSort, cls.SlideStatus).
		ScanAndCount(&out, &total, false)
	return
}

func (s *sSlideshow) Store(ctx context.Context, in *model.SlideshowFormInput) (err error) {
	err = dao.BlSlideshow.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		_, err = dao.BlSlideshow.Ctx(ctx).Data(in).Insert()
		return err
	})
	return
}

func (s *sSlideshow) Update(ctx context.Context, id uint64, in *model.SlideshowFormInput) (err error) {
	cls := dao.BlSlideshow.Columns()
	err = dao.BlSlideshow.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		_, err = dao.BlSlideshow.Ctx(ctx).Where(cls.Id, id).Data(in).Update()
		return err
	})
	return
}

func (s *sSlideshow) Destroy(ctx context.Context, ids []uint64) (err error) {
	var (
		check bool
		cls   = dao.BlSlideshow.Columns()
		m     = dao.BlSlideshow.Ctx(ctx)
	)

	ids = utils.UniqueIds(ids)
	if check, err = m.WhereIn(cls.Id, ids).Exist(); err != nil {
		return err
	} else if !check {
		return gerror.New("操作失败")
	}

	err = dao.BlSlideshow.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		_, err = m.WhereIn(cls.Id, ids).Delete()
		return err
	})
	return
}
